#pragma once
#include <iostream>
#include <sys/epoll.h>
#include <string.h>
#include "log.hpp"

extern Log lg;
class EPoller
{
    static const int size = 128;

public:
    EPoller()
    {
        epfd_ = epoll_create(size);
        if (epfd_ == -1)
        {
            lg(Error, "epoll_create error,strerr:%s", strerror(errno));
        }
        else
        {
            lg(Info, "epoll_create success,epfd:%d", epfd_);
        }
    }

    int EpollWait(struct epoll_event revent[], int num)
    {
        int n = epoll_wait(epfd_, revent, num, timeout);
        return n;
    }

    int Epollerupdata(int op, int fd, uint32_t event)
    {
        int n = 0;
        std::cout<<"op: "<<op<<",fd: "<<fd<<",event"<<event<<std::endl;
        if (op == EPOLL_CTL_DEL)
        {

            n = epoll_ctl(epfd_, op, fd, nullptr);
            if (n != 0)
            {
                lg(Error, "epoll_ctl error");
            }
        }
        else
        {
            struct epoll_event ev;
            ev.events = event;
            ev.data.fd = fd;
            n = epoll_ctl(epfd_, op, fd, &ev);
            if (n != 0)
            {
                lg(Error, "epoll_ctl error");
            }
        }
        return n;
    }
    ~EPoller()
    {
        if (epfd_ >= 0)
            close(epfd_);
    }

private:
    int epfd_;
    int timeout{5000};
};